package com.jsoup.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jsoup.bean.User;
import com.jsoup.service.UserService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/userManage")
public class UserManageController {

    @Resource
    private UserService userService;

    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @RequestMapping("/deleteUser")
    @RequiresRoles("admin")
    @ResponseBody
    public Object deleteUser(@RequestParam(value = "userId") Integer userId) {
        Map<Object, Object> map = new HashMap<>();
        int count = userService.deleteByPrimaryKey(userId);
        if (count > 0) {
            map.put("result", "success");
        }
        return map;
    }

    /**
     * 模糊搜索用户
     *
     * @param pn
     * @param content
     * @param model
     * @return
     */
    @RequestMapping("searchUser")
    @RequiresRoles("admin")
    public String searchUser(@RequestParam(value = "pn", defaultValue = "1") String pn,
                             @RequestParam(value = "content") String content,
                             Model model) {
        int pageNo = 1;
        try {
            pageNo = Integer.valueOf(pn);
        } catch (Exception e) {

        }
        content = content.trim().replaceAll(" ", "");
        User user = new User();
        user.setUserName(content);
        PageHelper.startPage(pageNo, 10);
        List<User> userList = userService.searchUser(user);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        model.addAttribute("pageInfo", pageInfo);
        return "manage-user";
    }


    /**
     * 用户列表
     *
     * @param pn
     * @param model
     * @return
     */
    @RequestMapping("/userList")
    @RequiresRoles("admin")
    public String userList(@RequestParam(value = "pn", defaultValue = "1") String pn, Model model) {
        int pageNo = 1;
        try {
            pageNo = Integer.valueOf(pn);
        } catch (Exception e) {

        }
        PageHelper.startPage(pageNo, 10);
        User user = new User();
        user.setUserLevelId(2);
        List<User> userList = userService.selectUser(user);
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        model.addAttribute("pageInfo", pageInfo);
        return "manage-user";
    }

}
